<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有!                                 |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: Xmh<xiangminghu@clcw.com.cn>                                   |
// +------------------------------------------------------------------------+
//
namespace AuctionCore\Agent;


use AuctionCore\CarResource\Car;
use AuctionCore\CarResource\CarModel;
use AuctionCore\ClcwUser\ClcwUser;
use AuctionCore\Common\PhpRedis;
use AuctionCore\System\SystemConf;

class RewardLog
{
    private $aid = null;

    public function __construct($aid)
    {
        $this->aid = $aid;
    }

    /**
     * 现金管理列表
     *
     * @param $page
     * @param $page_size
     * @param $params
     *
     * @return array
     */
    public static function getRewardCashLogList($page, $page_size, $params)
    {
        $page = $page < 1 ? 1 : (int)$page;
        $page_size = $page_size < 1 ? 10 : (int)$page_size;
        $map = [];
        $clcwUser = new ClcwUser();
        /**
         * 搜索条件：1、红包ID 2、红包类型 3、经纪人UID 4、经纪人帐号 5、车辆ID 6、开始时间 7、结束时间
         */
        if ($params['c_id']) {
            $map['cl.id'] = ['eq', trim($params['c_id'])];
        }
        if ($params['c_type']) {
            $map['cl.reward_type'] = ['eq', $params['c_type'], ['neq', '5']];
        } else {
            $map['cl.reward_type'] = ['neq', '5'];
        }
        if ($params['agent_uid']) {
            $map['a.uid'] = ['eq', trim($params['agent_uid'])];
        }
        if ($params['agent_phone']) {
            $agent_phone = trim($params['agent_phone']);
            $user = $clcwUser->getUserInfoByMobile($agent_phone);
            $agent = Agent::get_detail_by_uid($user['user_id']);
            $map['cl.aid'] = ['eq', $agent['aid']];
        }
        if ($params['car_no']) {
            $car_no = trim($params['car_no']);
            $car_detail = Car::getCarBySno($car_no);
            $map['cl.car_id'] = ['eq', $car_detail['car_id']];
        }
        if ($params['start_time']) {
            $map['cl.create_time'] = ['egt', strtotime($params['start_time'] . ' 00:00:00')];
        }
        if ($params['end_time']) {
            $map['cl.create_time'] = ['elt', strtotime($params['end_time'] . ' 23:59:59')];
        }
        if ($params['start_time'] && $params['end_time']) {
            $map['cl.create_time'] = [
                ['egt', strtotime($params['start_time'] . ' 00:00:00')],
                ['elt', strtotime($params['end_time'] . ' 23:59:59')]
            ];
        }
        $map['cl.type'] = ['eq', 1];
        $cols = "cl.id,cl.aid,cl.reward_type,cl.cash,cl.car_id,cl.create_time,a.uid";
        $order = "cl.id DESC";
        $total = M('reward_cash_log', 'clcw_', 'DB_CLCW')->alias("cl")
            ->join('clcw_agent as a ON cl.aid=a.aid')
            ->where($map)->count();
        $reward_total = M('reward_cash_log', 'clcw_', 'DB_CLCW')->alias("cl")
            ->field('SUM(cash) as reward_cash_total')
            ->join('clcw_agent as a ON cl.aid=a.aid')
            ->where($map)->find();
        $list = M('reward_cash_log', 'clcw_', 'DB_CLCW')->alias("cl")->field($cols)
            ->join('clcw_agent as a ON cl.aid=a.aid')
            ->where($map)
            ->order($order)
            ->page($page)
            ->limit($page_size)
            ->select();
//        echo M()->getLastSql();
        if (!empty($list)) {
            $cm = new CarModel();
            foreach ($list as $k => $v) {
                $info = $clcwUser->getClcwUserInfo($v['uid']);
                $list[$k]['agent_user'] = $info['mobile'];
                if (!empty($v['car_id'])) {
                    $car = new Car($v['car_id']);
                    $car_detail = $car->detail();
                    if (!empty($car_detail)) {
                        $series = $cm->get_model_by_id($car_detail['series_id'], 'series');
                        $list[$k]['sno'] = $car_detail['sno'];
                        $list[$k]['car_model_show'] = $series['name'] . ' ' . $car_detail['car_cc'] . ($car_detail['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $car_detail['gearbox']);;
                    }
                }
                $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            }
        }
        $result = [
            'list'         => $list,
            'total'        => $total,
            'reward_total' => sprintf("%01.2f", $reward_total['reward_cash_total'])
        ];
        return $result;
    }

    /**
     * 积分管理列表
     *
     * @param $page
     * @param $page_size
     * @param $params
     *
     * @return array
     */
    public static function getRewardIntegralLogList($page, $page_size, $params)
    {
        $page = $page < 1 ? 1 : (int)$page;
        $page_size = $page_size < 1 ? 10 : (int)$page_size;
        $map = [];
        $clcwUser = new ClcwUser();
        if ($params['c_id']) {
            $map['il.id'] = ['eq', trim($params['c_id'])];
        }
        if ($params['c_type']) {
            $map['il.reward_type'] = ['eq', $params['c_type'], ['neq', '5']];
        } else {
            $map['il.reward_type'] = ['neq', '5'];
        }
        if ($params['agent_uid']) {
            $map['a.uid'] = ['eq', trim($params['agent_uid'])];
        }
        if ($params['agent_phone']) {
            $agent_phone = trim($params['agent_phone']);
            $user = $clcwUser->getUserInfoByMobile($agent_phone);
            $agent = Agent::get_detail_by_uid($user['user_id']);
            $map['il.aid'] = ['eq', $agent['aid']];
        }
        if ($params['car_no']) {
            $car_no = trim($params['car_no']);
            $car_detail = Car::getCarBySno($car_no);
            $map['il.car_id'] = ['eq', $car_detail['car_id']];
        }
        if ($params['start_time']) {
            $map['il.create_time'] = ['egt', strtotime($params['start_time'] . ' 00:00:00')];
        }
        if ($params['end_time']) {
            $map['il.create_time'] = ['elt', strtotime($params['end_time'] . ' 23:59:59')];
        }
        if ($params['start_time'] && $params['end_time']) {
            $map['il.create_time'] = [
                ['egt', strtotime($params['start_time'] . ' 00:00:00')],
                ['elt', strtotime($params['end_time'] . ' 23:59:59')]
            ];
        }
        $map['il.type'] = ['eq', 1];
        $cols = "il.id,il.aid,il.reward_type,il.integral,il.car_id,il.create_time,a.uid";
        $order = "il.id DESC";
        $total = M('reward_integral_log', 'clcw_', 'DB_CLCW')->alias("il")
            ->join('clcw_agent as a ON il.aid=a.aid')
            ->where($map)->count();
        $reward_total = M('reward_integral_log', 'clcw_', 'DB_CLCW')->alias("il")
            ->field('SUM(integral) as reward_integral_total')
            ->join('clcw_agent as a ON il.aid=a.aid')
            ->where($map)->find();
        $list = M('reward_integral_log', 'clcw_', 'DB_CLCW')->alias("il")->field($cols)
            ->join('clcw_agent as a ON il.aid=a.aid')
            ->where($map)
            ->order($order)
            ->page($page)
            ->limit($page_size)
            ->select();
//        echo M()->getLastSql();
        if (!empty($list)) {
            $cm = new CarModel();
            foreach ($list as $k => $v) {
                $info = $clcwUser->getClcwUserInfo($v['uid']);
                $list[$k]['agent_user'] = $info['mobile'];
                if (!empty($v['car_id'])) {
                    $car = new Car($v['car_id']);
                    $car_detail = $car->detail();
                    if (!empty($car_detail)) {
                        $series = $cm->get_model_by_id($car_detail['series_id'], 'series');
                        $list[$k]['sno'] = $car_detail['sno'];
                        $list[$k]['car_model_show'] = $series['name'] . ' ' . $car_detail['car_cc'] . ($car_detail['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $car_detail['gearbox']);;
                    }
                }
                $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            }
        }
        $result = [
            'list'         => $list,
            'total'        => $total,
            'reward_total' => $reward_total['reward_integral_total'] + 0
        ];
        return $result;
    }

    /**
     * 成长值管理列表
     *
     * @param $page
     * @param $page_size
     * @param $params
     *
     * @return array
     */
    public static function getRewardGrowthLogList($page, $page_size, $params)
    {
        $page = $page < 1 ? 1 : (int)$page;
        $page_size = $page_size < 1 ? 10 : (int)$page_size;
        $map = [];
        $clcwUser = new ClcwUser();
        /**
         * 搜索条件：1、红包ID 2、红包类型 3、经纪人UID 4、经纪人帐号 5、车辆ID 6、开始时间 7、结束时间
         */
        if ($params['c_id']) {
            $map['gl.id'] = ['eq', trim($params['c_id'])];
        }
        if ($params['c_type']) {
            $map['gl.reward_type'] = ['eq', $params['c_type'], ['neq', '5']];
        } else {
            $map['gl.reward_type'] = ['neq', '5'];
        }
        if ($params['agent_uid']) {
            $map['a.uid'] = ['eq', trim($params['agent_uid'])];
        }
        if ($params['agent_phone']) {
            $agent_phone = trim($params['agent_phone']);
            $user = $clcwUser->getUserInfoByMobile($agent_phone);
            $agent = Agent::get_detail_by_uid($user['user_id']);
            $map['gl.aid'] = ['eq', $agent['aid']];
        }
        if ($params['car_no']) {
            $car_no = trim($params['car_no']);
            $car_detail = Car::getCarBySno($car_no);
            $map['gl.car_id'] = ['eq', $car_detail['car_id']];
        }
        if ($params['start_time']) {
            $map['gl.create_time'] = ['egt', strtotime($params['start_time'] . ' 00:00:00')];
        }
        if ($params['end_time']) {
            $map['gl.create_time'] = ['elt', strtotime($params['end_time'] . ' 23:59:59')];
        }
        if ($params['start_time'] && $params['end_time']) {
            $map['gl.create_time'] = [
                ['egt', strtotime($params['start_time'] . ' 00:00:00')],
                ['elt', strtotime($params['end_time'] . ' 23:59:59')]
            ];
        }
        $map['gl.type'] = ['eq', 1];
        $cols = "gl.id,gl.aid,gl.reward_type,gl.growth,gl.car_id,gl.create_time,a.uid";
        $order = "gl.id DESC";
        $total = M('reward_growth_log', 'clcw_', 'DB_CLCW')->alias("gl")
            ->join('clcw_agent as a ON gl.aid=a.aid')
            ->where($map)->count();
        $reward_total = M('reward_growth_log', 'clcw_', 'DB_CLCW')->alias("gl")
            ->field('SUM(growth) as reward_growth_total')
            ->join('clcw_agent as a ON gl.aid=a.aid')
            ->where($map)->find();
        $list = M('reward_growth_log', 'clcw_', 'DB_CLCW')->alias("gl")->field($cols)
            ->join('clcw_agent as a ON gl.aid=a.aid')
            ->where($map)
            ->order($order)
            ->page($page)
            ->limit($page_size)
            ->select();
//        echo M()->getLastSql();
        if (!empty($list)) {
            $cm = new CarModel();
            foreach ($list as $k => $v) {
                $info = $clcwUser->getClcwUserInfo($v['uid']);
                $list[$k]['agent_user'] = $info['mobile'];
                if (!empty($v['car_id'])) {
                    $car = new Car($v['car_id']);
                    $car_detail = $car->detail();
                    if (!empty($car_detail)) {
                        $series = $cm->get_model_by_id($car_detail['series_id'], 'series');
                        $list[$k]['sno'] = $car_detail['sno'];
                        $list[$k]['car_model_show'] = $series['name'] . ' ' . $car_detail['car_cc'] . ($car_detail['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $car_detail['gearbox']);;
                    }
                }
                $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            }
        }
        $result = [
            'list'         => $list,
            'total'        => $total,
            'reward_total' => $reward_total['reward_growth_total'] + 0
        ];
        return $result;
    }


    /**
     * @param $id
     * @param $data
     *
     * @return bool
     */
    public static function update_reward_cash_log($id, $data)
    {
        if ($id < 1 || empty($data)) {
            return false;
        }
        return M('reward_cash_log', 'clcw_', 'DB_CLCW')->where(['id' => $id])->save($data);
    }


    /**
     * 新增奖励记录 - 现金
     *
     * @param     $rId
     * @param     $aid
     * @param     $otherAid
     * @param     $type
     * @param     $cash
     * @param int $type
     * @param int $carId
     *
     * @return bool|mixed
     */
    public static function addCashLog($rId, $aid, $otherAid, $type, $cash, $carId = 0)
    {
        if (intval($rId) < 1 || intval($aid) < 1 || $type < 1) {
            return false;
        }
        $agentInfo = Agent::getDetailByAid($aid);
        $otherAgentInfo = Agent::getDetailByAid($otherAid);
        if (empty($agentInfo)) {
            return false;
        }
        $time = time();
        $data = [
            'r_id'        => $rId,
            'aid'         => $aid,
            'other_aid'   => $otherAid,
            'type'        => 1,
            'reward_type' => $type,
            'cash'        => $cash,
            'car_id'      => $carId,
            'create_time' => $time
        ];
        M('', 'clcw_', 'DB_CLCW')->startTrans();
        $ret = M('reward_cash_log', 'clcw_', 'DB_CLCW')->add($data);
        $clcwUser = new ClcwUser();
        $other_user_info = $clcwUser->getClcwUserInfo($otherAgentInfo['uid']);
        //现金奖励
        $ret1 = $clcwUser->change_user_money($agentInfo['uid'], 3, '自己 促成 客户 ' . showHideMobile($otherAgentInfo['mobile']) . ' 成功卖车。', $cash);
        if (!$ret) {
            Log::record("reward_log插入失败", "ERR", true);
            M('', 'clcw_', 'DB_CLCW')->rollback();
            return false;
        }
        if (!$ret1) {
            Log::record("更新经纪人用户金额信息失败", "ERR", true);
            M('', 'clcw_', 'DB_CLCW')->rollback();
            return false;
        }
        M('', 'clcw_', 'DB_CLCW')->commit();
        return true;
    }


    /**
     * 新增奖励记录 - 积分
     *
     * @param     $rId
     * @param     $aid
     * @param     $otherAid
     * @param     $type
     * @param     $integral
     * @param int $type
     * @param int $carId
     *
     * @return bool|mixed
     */
    public static function addIntegralLog($rId, $aid, $otherAid, $type, $integral, $carId = 0)
    {
        if (intval($rId) < 1 || intval($aid) < 1 || $type < 1) {
            return false;
        }
        $agentInfo = Agent::getDetailByAid($aid);
        if (empty($agentInfo)) {
            return false;
        }
        $time = time();
        $data = [
            'r_id'        => $rId,
            'aid'         => $aid,
            'other_aid'   => $otherAid,
            'type'        => 1,
            'reward_type' => $type,
            'integral'    => $integral,
            'car_id'      => $carId,
            'create_time' => $time
        ];
        M('', 'clcw_', 'DB_CLCW')->startTrans();
        $ret = M('reward_integral_log', 'clcw_', 'DB_CLCW')->add($data);
        //积分奖励
//        $clcwUser = new ClcwUser();
//        $ret1 = $clcwUser->change_user_score($agentInfo['uid'], 12, '客户卖车成功直接积分奖励', $integral);
        $redis = new PhpRedis(0);
        $ret1 = $redis->lpush(C('REDIS_KEY')['biz_queue'], json_encode(
                [
                    'bizContent' =>
                        [
                            'scoreType' => 12,
                            'score'     => (int)$integral,
//                            'remark' => '客户卖车成功直接积分奖励',
                            'remark'    => '',
                            'userId'    => (int)$agentInfo['uid']
                        ],
                    'bizType'    => 5
                ]
            )
        );
        if (!$ret) {
            Log::record("reward_log插入失败", "ERR", true);
            M('', 'clcw_', 'DB_CLCW')->rollback();
            return false;
        }
        if (!$ret1) {
            Log::record("更新经纪人用户积分信息失败", "ERR", true);
            M('', 'clcw_', 'DB_CLCW')->rollback();
            return false;
        }
        M('', 'clcw_', 'DB_CLCW')->commit();
        return true;
    }

    /**
     * 新增奖励记录 - 成长值
     *
     * @param     $rId
     * @param     $aid
     * @param     $otherAid
     * @param     $type
     * @param     $growth
     * @param int $type
     * @param int $carId
     *
     * @return bool|mixed
     */
    public static function addGrowthLog($rId, $aid, $otherAid, $type, $growth, $carId = 0)
    {
        if (intval($rId) < 1 || intval($aid) < 1 || $type < 1) {
            return false;
        }
        $agentInfo = Agent::getDetailByAid($aid);
        if (empty($agentInfo)) {
            return false;
        }
        $time = time();
        $data = [
            'r_id'        => $rId,
            'aid'         => $aid,
            'other_aid'   => $otherAid,
            'type'        => 1,
            'reward_type' => $type,
            'growth'      => $growth,
            'car_id'      => $carId,
            'create_time' => $time
        ];
        M('', 'clcw_', 'DB_CLCW')->startTrans();
        $ret = M('reward_growth_log', 'clcw_', 'DB_CLCW')->add($data);
        //成长值奖励
//        $clcwUser = new ClcwUser();
//        $ret1 = $clcwUser->change_user_exp($agentInfo['uid'], 12, '客户卖车成功直接成长值奖励', $growth);
        $redis = new PhpRedis(0);
        $ret1 = $redis->lpush(C('REDIS_KEY')['biz_queue'], json_encode(
                [
                    'bizContent' =>
                        [
                            'expType' => 12,
                            'exp'     => (int)$growth,
//                            'remark' => '客户卖车成功直接成长值奖励',
                            'remark'  => '',
                            'userId'  => (int)$agentInfo['uid']
                        ],
                    'bizType'    => 6
                ]
            )
        );
        if (!$ret) {
            Log::record("reward_log插入失败", "ERR", true);
            M('', 'clcw_', 'DB_CLCW')->rollback();
            return false;
        }
        if (!$ret1) {
            Log::record("更新经纪人成长值信息失败", "ERR", true);
            M('', 'clcw_', 'DB_CLCW')->rollback();
            return false;
        }
        M('', 'clcw_', 'DB_CLCW')->commit();
        return true;
    }


    /**
     * 新增奖励记录 - 更新经纪人累积金额
     *
     * @param     $rId
     * @param     $aid
     * @param     $otherAid
     * @param     $type
     * @param     $cash
     * @param     $integral
     * @param     $growth
     * @param int $type
     * @param int $carId
     *
     * @return bool|mixed
     */
    public static function addLog($rId, $aid, $otherAid, $type, $cash, $integral, $growth, $carId = 0)
    {
        if (intval($rId) < 1 || intval($aid) < 1 || $type < 1) {
            return false;
        }
        $agentInfo = Agent::getDetailByAid($aid);
        if (empty($agentInfo)) {
            return false;
        }
        $time = time();
        $data = [
            'r_id'        => $rId,
            'aid'         => $aid,
            'other_aid'   => $otherAid,
            'reward_type' => $type,
            'cash'        => $cash,
            'integral'    => $integral,
            'growth'      => $growth,
            'car_id'      => $carId,
            'type'        => 1,
            'create_time' => $time
        ];
        //直接交易配置
        $sale_car_award = SystemConf::getConfByName('SALE_CAR_AWARD');
        $award_conf = json_decode($sale_car_award['value'], true);
        M('', 'clcw_', 'DB_CLCW')->startTrans();
        $ret = M('reward_log', 'clcw_', 'DB_CLCW')->add($data);
        $clcwUser = new ClcwUser();
        //现金奖励
        $ret1 = $ret2 = $ret3 = true;
        if ($award_conf['cash']['isAward']) {
            $ret1 = $clcwUser->change_user_money($agentInfo['uid'], 3, '客户卖车成功直接现金奖励', $cash);
        }
        //积分奖励
        if ($award_conf['integral']['isAward']) {
            $ret2 = $clcwUser->change_user_score($agentInfo['uid'], 12, '客户卖车成功直接积分奖励', $integral);
        }
        //成长值奖励
        if ($award_conf['growth']['isAward']) {
            $ret3 = $clcwUser->change_user_exp($agentInfo['uid'], 12, '客户卖车成功直接成长值奖励', $growth);
        }
        if (!$ret) {
            Log::record("reward_log插入失败", "ERR", true);
            M('', 'clcw_', 'DB_CLCW')->rollback();
            return false;
        }
        if (!$ret1 || !$ret2 || !$ret3) {
            Log::record("更新经纪人信息失败", "ERR", true);
            M('', 'clcw_', 'DB_CLCW')->rollback();
            return false;
        }
        M('', 'clcw_', 'DB_CLCW')->commit();
        return true;
    }


}